import React, { Fragment, useEffect, useRef,useState } from 'react';
import {useDrop,useDrag} from 'react-dnd';
import './index1.css';
import  ItemTypes  from './ItemTypes';
import {CurveContainer} from '../curveDemo1/curveContainer';
import {DepthDemo} from '../depthDemo1';
import {YxDemo} from '../yxDemo1';
import EditDaoForm from '../../Modal/edit-dao-form ';
import {Modal} from 'antd';
import {useSelector,useDispatch} from 'react-redux';   // 代替connect
import {deleteDao,deleteMbDao,isUpdatePages,editMbDaoInfo, editDaoDataList1Info} from '../../../redux/actions';
import SplitPane, { Pane } from 'react-split-pane';

let count = 0;


export const Dao = ({ id, title, index, curves, moveDao, isFixed, scrollLeft, depthDaoCount }) => {   // 接收传入的属性:道id、道名称、道索引、道中曲线、isFixed：是否固定 道头
  const ref = useRef(null)

  const [, drop] = useDrop({   // 放置对象  
    accept: ItemTypes.DAO,
    hover (item, monitor) {  
      if (!ref.current) {
        return
      }
      const dragIndex = item.index    
      const hoverIndex = index

      // Don't replace items with themselves   
      if (dragIndex === hoverIndex) {
        return
      }

      // Determine rectangle on screen
      const hoverBoundingRect = ref.current?.getBoundingClientRect()

      // Get vertical middle
      const hoverMiddleY =
        (hoverBoundingRect.right - hoverBoundingRect.left) / 2

      // Determine mouse position
      const clientOffset = monitor.getClientOffset()

      // Get pixels to the top
      const hoverClientY = clientOffset.x - hoverBoundingRect.left

      // Only perform the move when the mouse has crossed half of the items height
      // When dragging downwards, only move when the cursor is below 50%
      // When dragging upwards, only move when the cursor is above 50%

      // Dragging downwards
      if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
        return
      }

      // Dragging upwards
      if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
        return
      }

      // Time to actually perform the action
      moveDao(dragIndex, hoverIndex)

      // Note: we're mutating the monitor item here!
      // Generally it's better to avoid mutations,
      // but it's good here for the sake of performance
      // to avoid expensive index searches.
      item.index = hoverIndex
    },
  })

  const [{isDragging}, drag] = useDrag({   // 拖拽 对象
    item: { type: ItemTypes.DAO, id, index },
    collect: (monitor) => ({
      isDragging: monitor.isDragging(),
    }),    
  })

  const [isSelectCurve, setIsSelectCurve] = useState(false);
  const [visible, setVisible] = useState(false);
  const [formRef, setFormRef] = useState('');
  const [hLine, setHLine] = useState(true);
  const [vLine, setVLine] = useState(true);
  
  const dispatch = useDispatch()   // 像state 更改 数据
  const daosDataList = useSelector(state => state.daosDataList1);   // 从state中取 数据
  

  const mb_dao = useSelector(state => state.mbData.mb_dao)
  let dao_width,line_dao_width=0;

  if(mb_dao)
  {
    mb_dao.map(item=>{
      if(item.id==id){
        dao_width=item.dao_width;
      }
    });
    for(let i=0;i<mb_dao.length&&i<index;i++){
      if(mb_dao[i].type=="line-dao"){
        line_dao_width+=mb_dao[i].dao_width;
      }
    }
    // console.log("dao",index,line_dao_width);
  }
   




  const editDaoLine = () => {   // 更新 道 的 横/纵格线
    const checkbox = formRef.current.getFieldValue('checkbox');
    const vgridNumber = formRef.current.getFieldValue('vgridNumber');
    const hgridNumber = formRef.current.getFieldValue('hgridNumber');
    const vlineType = formRef.current.getFieldValue('vlineType');
    const hlineType = formRef.current.getFieldValue('hlineType');
    const dao_width = formRef.current.getFieldValue('dao_width');

    const data={
      vgridNumber,
      hgridNumber,
      id,
      vlineType,
      hlineType,
      dao_width
    }
    console.log(data);

    setVLine(false);
    setHLine(false);
    checkbox.map((item)=>{
      if(item==='v-line'){  // 判断纵格线
        setVLine(true);
      }else if(item==='h-line'){  // 判断横格线
        setHLine(true);
      }
    })
    setVisible(false);

    dispatch(editMbDaoInfo(data))

    dispatch(editDaoDataList1Info(data))
  }



  const handleCancel = () => {
    setVisible(false);
  }

  const onClickDaoTitle = () => {   // 点击、双击 道
    count += 1;
    setTimeout(() => {
      if(count === 1){
        setIsSelectCurve(!isSelectCurve);
      }else if(count === 2){
        setVisible(true);
      }
      count = 0;
    },300)
  }

  const updatePages = useSelector(state => state.updatePages);   // 从state中取 数据
  const deleteDaos = (daoId) => {  // 删除道
    dispatch(deleteDao(daoId)); 
    dispatch(isUpdatePages(!updatePages));  //及时更新页面
  };

  drag(drop(ref))   // 既可以拖拽，也可以放置
  if(title === '深度'){
    return ( 
      <div 
        ref={ref} 
        className={isSelectCurve ? (isFixed? "depth-dao-select-fixed1":"depth-dao-select1") : (isFixed? "depth-dao-fixed1":"depth-dao1")} 
      > 
        {/* 水平滚动时，fixed固定的头部 也要同步滚动，因此要及时更新 left */}
        <div 
          className="dao-title1" 
          onClick={onClickDaoTitle} 
          style={{left: 279 + (depthDaoCount*52) + ((index-depthDaoCount)*200) - scrollLeft }}
        >
          {title}
          {/* {isSelectCurve? <i className="iconfont" style={{float:'right',paddingRight:2,cursor:"pointer"}} onClick={() => deleteDaos(id)}>&#xe614;</i> : null} */}
        </div>  
        <DepthDemo 
          daoId={id} daoIndex={index}
          leftData={279 + (depthDaoCount*52) + ((index-depthDaoCount)*200) - scrollLeft}
        /> 
      </div>  
    )    
  }else if(title === '岩性道'){
    return(
      <div ref={ref} className={isSelectCurve ? (isFixed ? "dao-select-fixed1":"dao-select1") : (isFixed ? "dao-fixed1":"dao1")}>   
        <div 
          className="dao-title1" 
          onClick={onClickDaoTitle} 
          style={{left: 279 + (depthDaoCount*52) + ((index-depthDaoCount)*200) - scrollLeft }}
        >
          {title}
          {/* {isSelectCurve? <i className="iconfont" style={{float:'right',paddingRight:5,cursor:"pointer"}} onClick={() => deleteDaos(id)}>&#xe614;</i> : null} */}
        </div>  
        <YxDemo 
          daoId={id} daoIndex={index}
          leftData={279 + (depthDaoCount*52) + ((index-depthDaoCount)*200) - scrollLeft}
        /> 
      </div>  
    )  
  }else{
    return (
      <Fragment >  
        <div ref={ref} className={isSelectCurve ? (isFixed ? "dao-select-fixed1":"dao-select1") : (isFixed ? "dao-fixed1":"dao1")} > 
          <div 
            className="dao-title1" 
            onClick={onClickDaoTitle} 
            style={{
              width:dao_width-2,
              left: 279 + (depthDaoCount*52) + line_dao_width - scrollLeft 
            }}
          >
            {title}
            {/* {isSelectCurve? <i className="iconfont" style={{float:'right',paddingRight:5,cursor:"pointer"}} onClick={() => deleteDaos(id)}>&#xe614;</i> : null} */}
          </div>
          <CurveContainer 
            daoId={id} daoIndex={index} curves ={curves} vLine={vLine} hLine={hLine} 
            leftData={279 + (depthDaoCount*52) + line_dao_width - scrollLeft}
          />    
        </div> 

        <Modal
          title="道属性"
          visible={visible === true}
          onOk={editDaoLine}
          onCancel={handleCancel}
          okText="确定"
          cancelText="取消"
          destroyOnClose={true}
        >
          <EditDaoForm 
            id = {id}
            hLine = {hLine}
            vLine = {vLine}
            setForm = {(formRef) => {setFormRef(formRef)}}   
          />
        </Modal>
      </Fragment>
    )
  }
} 


 
